<?php
namespace app\common\model;
use think\Model;
use think\Db;
class Order extends Model
{
    //定义表名
    protected $name = 'massage_service_order_list';
     protected $append = [
         'coach_info',
         'order_goods',
         'all_goods_num',
         'address_info'
     ];
    /**
     * @param $value
     * @param $data
     * @功能说明:地址信息
     * @author chenniang
     * @DataTime: 2021-04-08 10:11
     */
     public function getAddressInfoAttr($value,$data){
         if(!empty($data['id'])){
             $address_model = new OrderAddress();
             $address_info = $address_model->dataInfo(['order_id'=>$data['id']]);
             return $address_info;
         }
     }
    /**
     * @param $value
     * @param $data
     * @功能说明:总商品数量
     * @author chenniang
     * @DataTime: 2021-03-25 14:39
     */
     public function getAllGoodsNumAttr($value,$data){
         if(!empty($data['id'])){
             $order_goods_model = new OrderGoods();
             $dis = [
                 'order_id' => $data['id']
             ];
             $num = $order_goods_model->where($dis)->sum('num');
             return $num;
         }
     }
    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:05
     * @功能说明:子订单信息
     */
     public function getOrderGoodsAttr($value,$data){
         if(!empty($data['id'])){
             $order_goods_model = new OrderGoods();
             $dis = [
                 'order_id' => $data['id']
             ];
             $list = $order_goods_model->where($dis)->select()->toArray();
             return $list;
         }
     }
    /**
     * @param $value
     * @param $data
     * @功能说明:订单的团长信息
     * @author chenniang
     * @DataTime: 2021-03-19 16:49
     */
     public function getCoachInfoAttr($value,$data){
         if(!empty($data['coach_id'])){
             $cap_model = new Coach();
             $info = $cap_model->dataInfo(['id'=>$data['coach_id']]);
             return $info;
         }
     }
//
//    /**
//     * @author chenniang
//     * @DataTime: 2021-03-25 17:40
//     * @功能说明：生产二维码
//     */
//     public function getQrAttr($value,$data){
//
//
//         if(!empty($value)){
//
//             return $value;
//         }
//
//         if(!empty($data['pay_type'])&&$data['pay_type']>1&&!empty($data['id'])&&!empty($data['uniacid'])){
//
//             $qr_insert = [
//
//                 'id' => $data['id']
//             ];
//
//             $qr = $this->orderQr($qr_insert,$data['uniacid']);
//
//             if(!empty($qr)){
//
//                 $this->dataUpdate(['id'=>$data['id']],['qr'=>$qr]);
//
//                 return $qr;
//             }
//
//             return '';
//         }
//
//
//     }
//
//
//    /**
//     * @author chenniang
//     * @DataTime: 2020-10-27 15:42
//     * @功能说明:订单自提码
//     */
//    public function orderQr($input,$uniacid){
//
//        $data = longbingCreateWxCode($uniacid,$input,'master/pages/order/hexiao');
//
//        $data = transImagesOne($data ,['qr_path'] ,$uniacid);
//
//        $qr   = $data['qr_path'];
//
//        return $qr;
//    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:23
     * @功能说明:前端订单列表
     */
     public function indexDataList($dis,$mapor,$page=10){
         $data = $this->alias('a')
             ->join('massage_service_order_goods_list b','a.id = b.order_id','left')
             ->where($dis)
             ->where(function ($query) use ($mapor){
                 $query->whereOr($mapor);
             })
             ->field('a.*')
             ->group('a.id')
             ->order('a.id desc')
             ->paginate($page)
             ->toArray();
         if(!empty($data['data'])){
             foreach ($data['data'] as &$v){
                 $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                 $v['start_time']  = date('Y-m-d H:i',$v['start_time']);
                 $v['end_time']    = date('Y-m-d H:i',$v['end_time']);
             }
         }
         return $data;
     }
    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataList($dis,$page=10){
        $data = $this->alias('a')
                ->join('massage_service_coach_list b','a.coach_id = b.id')
                ->join('massage_service_order_goods_list c','a.id = c.order_id')
                ->join('massage_service_order_address d','a.id = d.order_id')
                ->join('massage_channel_list e','a.channel_id = e.id','left')
                ->join('massage_channel_cate f','f.id = e.cate_id','left')
                ->where($dis)
                ->field('a.*,b.coach_name,d.mobile,d.user_name,e.user_name as channel_name,f.title as channel')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();
        if(!empty($data['data'])){
            $user_model = new User();
            $refund_model = new RefundOrder();
            foreach ($data['data'] as &$v){
                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');
                $v['distance'] = distance_text($v['distance']);
                $v['refund_price'] = $refund_model->where(['order_id'=>$v['id'],'status'=>2])->sum('refund_price');
            }
        }
        return $data;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminOrderPrice($dis){
        $data = $this->alias('a')
            ->join('massage_service_coach_list b','a.coach_id = b.id')
            ->join('massage_service_order_goods_list c','a.id = c.order_id')
            ->join('massage_service_order_address d','a.id = d.order_id')
            ->join('massage_channel_list e','a.channel_id = e.id','left')
            ->join('massage_channel_cate f','f.id = e.cate_id','left')
            ->where($dis)
            ->column('a.id');
        $price = $this->where('id','in',$data)->sum('true_service_price');
        return round($price,2);
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataSelect($dis){
        $data = $this->alias('a')
            ->join('massage_service_coach_list b','a.coach_id = b.id')
            ->join('massage_service_order_goods_list c','a.id = c.order_id')
            ->join('massage_service_order_address d','a.id = d.order_id')
            ->join('massage_channel_list e','a.channel_id = e.id','left')
            ->join('massage_channel_cate f','f.id = e.cate_id','left')
            ->where($dis)
            ->field('a.*,b.coach_name,d.mobile,d.user_name,c.goods_id,c.goods_name,c.price,c.num,e.user_name as channel_name,f.title as channel')
            ->group('a.id,c.goods_id')
            ->order('a.id desc')
            ->select()
            ->toArray();
        if(!empty($data)){
            $user_model = new User();
            $refund_model = new RefundOrder();
            foreach ($data as &$v){
                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');
                $v['refund_price'] = $refund_model->where(['order_id'=>$v['id'],'status'=>2])->sum('refund_price');
            }
        }
        return $data;
    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){
        $data['create_time'] = time();
        $res = $this->insert($data);
        return $res;
    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){
        $res = $this->where($dis)->update($data);
        return $res;
    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){
        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();
        return $data;
    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){
        $data = $this->where($dis)->find();
        return !empty($data)?$data->toArray():[];
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-18 14:33
     * @功能说明:
     */
    public function datePrice($date,$uniacid,$cap_id=0,$end_time = '',$type=1){
        $end_time = !empty($end_time)?$end_time:$date+86399;
        $dis = [];
        $dis[] = ['transaction_id','<>',''];
        $dis[] = ['auto_refund','=',0];
        $dis[] = ['create_time','between',"$date,$end_time"];
        $dis[] = ['uniacid',"=",$uniacid];
        if(!empty($cap_id)){
            $dis[] = ['cap_id','=',$cap_id];
        }
        if($type==1){
            $price = $this->where($dis)->sum('pay_price');
            return round($price,2);
        }else{
            $count = $this->where($dis)->count();
            return $count;
        }
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-19 09:28
     * @功能说明:计算用户下单时候的各类金额
     */
    public function payOrderInfo($user_id,$cap_id,$lat=0,$lng=0,$car_type=0,$coupon=0){
        $car_model = new Car();
        $coupon_model = new Coupon();
        $coach_model = new Coach();
        $coach = $coach_model->dataInfo(['id'=>$cap_id]);
        //获取购物车里面的信息
        $car_list  = $car_model->carPriceAndCount($user_id,$cap_id);
        $car_list  = $coupon_model->orderCouponData($car_list,$coupon);
        $goods_price = $car_list['car_price'];
        $data['coupon_id']   = $car_list['coupon_id'];
        //购物车列表
        $data['order_goods'] = $car_list['list'];
        //优惠券优惠
        $data['discount']    = $car_list['total_discount'];
        //商品总价格
        $data['init_goods_price'] = round($goods_price,2);
        $data['goods_price'] = round($goods_price-$data['discount'],2);
        if($lat==0){
            $data['car_price'] = 0;
        }else{
            //车费
            $data['car_price'] = $this->getCarPrice($cap_id,$lat,$lng,$car_type);
        }
        //订单支付价
        $data['pay_price']   = round($data['goods_price']+$data['car_price'] ,2);
        $data['coach_id']    = $cap_id;
        if($lng==0){
            $data['distance'] = 0;
        }else{
            $data['distance'] = getDistances($coach['lng'],$coach['lat'],$lng,$lat);
        }
        return $data;
    }
    /**
     * @param $order
     * @功能说明:获取佣金数据
     * @author chenniang
     * @DataTime: 2022-06-13 13:42
     */
    public function getCashDataV2($order,$type=1){
        $coach_model = new Coach();
        $admin_model = new Admin();
        $comm_model  = new Commission();
        //下单
        if($type==1){
            $coach = $coach_model->dataInfo(['id'=>$order['coach_id']]);
            //技师等级
            $coach_level = $coach_model->getCoachLevel($order['coach_id'],$coach['uniacid']);
            //技师佣金比列
            $order['coach_balance'] = $coach_level['balance'];
            $admin = $admin_model->dataInfo(['id'=>$coach['admin_id']]);
            //平台抽层比列
            $order['admin_balance'] = !empty($admin)?$admin['balance']:0;
            $order['admin_id']      = $coach['admin_id'];
            //获取分销商的金额并添加分销记录
            $order['user_cash']     = $comm_model->commissionAddData($order,$order['admin_balance']);
        }
        //平台抽层
        $order['company_cash'] = round($order['admin_balance']*$order['true_service_price']/100,2);
        //剩下的钱 除开平台抽层 和用户分销
        $admin_cash = (100-$order['admin_balance'])/100*$order['true_service_price']-$order['user_cash'];
        //技师佣金
        $order['coach_cash'] = round($order['coach_balance']*$admin_cash/100,2);
        //加盟商佣金
        $order['admin_cash'] = !empty($order['admin_id'])?round((100-$order['coach_balance'])*$admin_cash/100,2):0;
        //增加分销记录
        if($type==1){
            //技师佣金记录
            $comm_model->coachCommission($order);
            //加盟商佣金记录
            $comm_model->adminCommission($order);
        }
        $arr = ['coach_balance','admin_balance','admin_id','user_cash','company_cash','coach_cash','admin_cash'];
        foreach ($arr as $value){
            if(key_exists($value,$order)){
                $list[$value] = $order[$value];
            }
        }
        return $list;
    }
    /**
     * @param $order
     * @功能说明:获取佣金数据（产品神逻辑）
     * @author chenniang
     * @DataTime: 2022-06-13 13:42
     */
    public function getCashData($order,$type=1){
        $coach_model = new Coach();
        $admin_model = new Admin();
        $comm_model  = new Commission();
        //下单
        if($type==1){
            $coach = $coach_model->dataInfo(['id'=>$order['coach_id']]);
            //技师等级
            $coach_level = $coach_model->getCoachLevel($order['coach_id'],$coach['uniacid']);
            //技师佣金比列
            $order['coach_balance'] = $coach_level['balance'];
            $admin = $admin_model->dataInfo(['id'=>$coach['admin_id']]);
            //平台抽层比列
            $order['admin_balance'] = !empty($admin)?$admin['balance']:0;
            $order['admin_id']      = $coach['admin_id'];
            //获取分销商的金额并添加分销记录
            $order['user_cash']     = $comm_model->commissionAddData($order,$order['admin_balance']);
        }
        //平台抽层
        $order['company_cash'] = round($order['admin_balance']*$order['true_service_price']/100,2);
        //技师佣金
        $order['coach_cash']   = round($order['coach_balance']*$order['true_service_price']/100,2);
        //剩下的佣金
        $admin_cash = $order['true_service_price'] - $order['user_cash'] - $order['coach_cash'];
        $admin_cash = $admin_cash>0?$admin_cash:0;
        $order['company_cash'] = $order['company_cash'] - $admin_cash>0?$admin_cash:$order['company_cash'];
        //加盟商佣金
        $order['admin_cash'] = $admin_cash - $order['company_cash']>0&&!empty($order['admin_id'])?round($admin_cash - $order['company_cash'],2):0;
        //增加分销记录
        if($type==1){
            //技师佣金记录
            $comm_model->coachCommission($order);
            //加盟商佣金记录
            $comm_model->adminCommission($order);
        }
        $arr = ['coach_balance','admin_balance','admin_id','user_cash','company_cash','coach_cash','admin_cash'];
        foreach ($arr as $value){
            if(key_exists($value,$order)){
                $list[$value] = $order[$value];
            }
        }
        return $list;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-07-09 17:43
     * @功能说明:计算车费
     */
    public function getCarPrice($coach_id,$lat,$lng,$car_type=1){
        if($car_type==0){
            return 0;
        }
        $coach_model = new Coach();
        $coach = $coach_model->dataInfo(['id'=>$coach_id]);
        $config_model = new CarPrice();
        $config = $config_model->dataInfo(['uniacid'=>$coach['uniacid']]);
        //起步距离
        $start = $config['start_distance'];
        //起步价
        $start_price = $config['start_price'];
        //每公里多少钱
        $to_price = $config['distance_price'];
        $distance = getDistances($coach['lng'],$coach['lat'],$lng,$lat);
        $distance = $distance/1000;
        //多少公里内免费
        if($distance<$config['distance_free']){
            return 0;
        }
        //超过起步距离
        if($distance>$start){
            $to_price = round($distance - $start,2)*$to_price;
            $total    = $to_price+$start_price;
            return round($total*2,2);
        }else{
            return round($start_price*2,2);
        }
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-22 11:31
     * @功能说明:订单支付回调
     */
    public function orderResult($order_code,$transaction_id){
        $order = $this->dataInfo(['order_code'=>$order_code]);
        if(!empty($order)&&$order['pay_type']==1){
            Db::startTrans();
            $update = [
                'transaction_id' => $transaction_id,
                'pay_type'       => 2,
                'pay_time'       => time(),
            ];
            $res = $this->dataUpdate(['id'=>$order['id']],$update);
            if($res==0){
                Db::rollback();
                return false;
            }
            //扣除余额
            if($order['balance']>0){
                $user_model  = new User();
                $water_model = new BalanceWater();
                $user = $user_model->dataInfo(['id'=>$order['user_id']]);
                //修改用户余额
                $res = $user_model->dataUpdate(['id'=>$order['user_id'],'lock'=>$user['lock']],['balance'=>$user['balance']-$order['pay_price'],'lock'=>$user['lock']+1]);
                if($res==0){
                    Db::rollback();
                    return false;
                }
                //添加余额流水
                $insert = [
                    'uniacid' => $order['uniacid'],
                    'user_id' => $order['user_id'],
                    'price'   => $order['pay_price'],
                    'order_id'=> $order['id'],
                    'add'     => 0,
                    'type'    => 2,
                    'before_balance' => $user['balance'],
                    'after_balance'  => $user['balance']-$order['pay_price'],
                ];
                $res = $water_model->dataAdd($insert);
                if($res==0){
                    Db::rollback();
                    return false;
                }
            }
            //分销
            $comm_model = new Commission();
            //将分销记录打开
            $comm_model->dataUpdate(['order_id'=>$order['id']],['status'=>1]);
            Db::commit();
            $notice_model = new NoticeList();
            //增加后台提醒
            $notice_model->dataAdd($order['uniacid'],$order['id'],1,$order['admin_id']);
            $coach_model = new Coach();
            //发送通知
            $coach_model->paySendMsg($order);
            //打印
            $print_model = new Printer();
            $print_model->printer($order['id'],0);
        }
        return true;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:31
     * @功能说明:团长冻结资金
     */
    public function capFrozenPrice($cap_id,$total=0,$toDay=0){
        $dis[] = ['cap_id','=',$cap_id];
        if($total==0){
            $dis[] = ['have_tx','=',0];
        }
        $dis[] = ['pay_type','>',1];
        if($toDay==1){
            //当日
            $price = $this->where($dis)->whereDay('create_time')->sum('cap_price');
        }else{
            $price = $this->where($dis)->sum('cap_price');
        }
        return round($price,2);
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:31
     * @功能说明:团长冻结资金
     */
    public function capFrozenCount($cap_id,$total=0,$toDay=0){
        $dis[] = ['cap_id','=',$cap_id];
        if($total==0){
            $dis[] = ['have_tx','=',0];
        }
        $dis[] = ['pay_type','>',1];
        if($toDay==1){
            //当日
            $price = $this->where($dis)->whereDay('create_time')->count();
        }else{
            $price = $this->where($dis)->count();
        }
        return $price;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-22 15:41
     * @功能说明:团长佣金到账
     */
    public function capArrPrice($uniacid,$cap_id=0){
        $dis[] = ['uniacid','=',$uniacid];
        $dis[] = ['pay_type','=',7];
        if(!empty($cap_id)){
            $dis[] = ['cap_id','=',$cap_id];
        }
        $dis[] = ['have_tx','=',0];
//        $dis[] = ['hx_time','<',time()-86400];
        $dis[] = ['hx_time','<',time()-60];
        $order = $this->where($dis)->field('id,cap_price,cap_id')->select()->toArray();
        if(!empty($order)){
            $cap_model = new Cap();
            $refund_model = new RefundOrder();
            foreach ($order as $value){
                //判断有无申请中的退款订单
                $refund_order = $refund_model->dataInfo(['order_id'=>$value['id'],'status'=>1]);
                if(empty($refund_order)){
                    //修改订单状态
                    $res = $this->where(['id'=>$value['id'],'have_tx'=>0])->update(['have_tx'=>1]);
                    //增加团长佣金
                    if($res==1){
                        $cap_cash = $value['cap_price'];
                        $cap_model->where(['id'=>$cap_id])->update(['cap_cash'=>Db::raw("cap_cash+$cap_cash")]);
                    }
                }
            }
        }
        return true;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-26 15:15
     * @功能说明:核销订单
     */
    public function hxOrder($order,$cap_id=0){
        $update = [
            'order_end_time' => time(),
            'pay_type'       => 7,
            'hx_user'        => $cap_id,
            //可申请退款的时间
            'can_tx_date'    => time()+$order['can_tx_time']*60*60
        ];
        $res = $this->dataUpdate(['id'=>$order['id']],$update);
        return $res;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){
        $dis[] = ['uniacid','=',$uniacid];
        $dis[] = ['pay_type','=',1];
        $dis[] = ['over_time','<',time()];
        if(!empty($user_id)){
            $dis[] = ['user_id','=',$user_id];
        }
        $order = $this->where($dis)->select()->toArray();
        if(!empty($order)){
            foreach ($order as $value){
                $this->cancelOrder($value);
            }
        }
        return true;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:退款
     */
    public function cancelOrder($order){
        Db::startTrans();
        $res = $this->dataUpdate(['id'=>$order['id'],'pay_type'=>1],['pay_type'=>-1]);
        if($res!=1){
            Db::rollback();
            return ['code'=>500,'msg'=>'取消失败'];
        }
        $goods_model = new Service();
        //退换库存
        foreach ($order['order_goods'] as $v){
            $res =  $goods_model->setOrDelStock($v['goods_id'],$v['num'],1);
            if(!empty($res['code'])){
                Db::rollback();
                return $res;
            }
        }
        //退换优惠券
        $coupon_model = new CouponRecord();
        $coupon_model->couponRefund($order['id']);
        Db::commit();
        return true;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-07-10 18:04
     * @功能说明:检查技师时间
     */
    public function checkTime($order,$start_time){
        $service_model = new Service();
        $coach_model   = new Coach();
        $order_model   = new Order();
        $total_long = 0;
        foreach ($order['order_goods'] as $v){
            $time_long = $service_model->where(['id'=>$v['service_id']])->value('time_long');
            $total_long+=$time_long*$v['num'];
        }
        $end_time = $start_time+$total_long*60;
        $coach = $coach_model->dataInfo(['id'=>$order['coach_id']]);
        $all_day = 1;
        //判断不是全体24小时上班
        if($coach['start_time']!=$coach['end_time']){
            $all_day = 0;
        }
        //判断是否隔夜
        $s_day = date('Y-m-d',$start_time);
        $e_day = date('Y-m-d',$end_time);
        //全天不判断
        if($all_day==0){
            //说明是隔天
//            if($s_day!=$e_day){
//
//                return ['code'=>500,'msg'=>'不在技师服务时间内,技师服务时间:'.$coach['start_time'].'-'.$coach['end_time']];
//
//            }
            //教练上班时间
            $coach_start_time = strtotime($coach['start_time'])-strtotime(date('Y-m-d',time()))+strtotime(date('Y-m-d',$start_time));
            //教练下班时间
            $coach_end_time   = strtotime($coach['end_time'])-strtotime(date('Y-m-d',time()))+strtotime(date('Y-m-d',$start_time));
            if($end_time<$coach_start_time){
                $coach_start_time -= 86400;
                $coach_end_time   -= 86400;
            }
            $coach_end_time = $coach_end_time>$coach_start_time?$coach_end_time:$coach_end_time+86400;
            if($start_time<$coach_start_time||$end_time>$coach_end_time){
               // dump(date('Y-m-d H:i',$start_time),date('Y-m-d H:i',$coach_start_time),date('Y-m-d H:i',$end_time),date('Y-m-d H:i',$coach_end_time));exit;
                return ['code'=>500,'msg'=>'不在技师服务时间内,技师服务时间:'.$coach['start_time'].'-'.$coach['end_time']];
            }
        }
        //检查该时间段是否被预约
        $where[] = ['coach_id','=',$order['coach_id']];
        $where[] = ['pay_type','not in',[-1]];
        $where[] = ['end_time','>',time()];
        $order_list = $order_model->where($where)->field('id,start_time,end_time')->select()->toArray();
        if(!empty($order_list)){
            foreach ($order_list as $value){
                //判断两个时间段是否有交集
                $res = is_time_cross($start_time,$end_time,$value['start_time'],$value['end_time']);
                if($res==false){
                    return ['code'=>500,'msg'=>'该技师该时间段已经被预约:'.date('Y-m-d H:i',$value['start_time']).'-'.date('Y-m-d H:i',$value['end_time']).'-'.$value['id']];
                }
            }
        }
        $arr = [
            'end_time' => $end_time,
            'time_long'=> $total_long
        ];
        return $arr;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-07-11 22:39
     * @功能说明:技师修改订单信息
     */
    public function coachOrdertext($input){
        $update['pay_type'] = $input['type'];
        switch ($input['type']){
            case 3:
                $update['receiving_time'] = time();
                break;
            case 4:
                $update['serout_time'] = time();
                break;
            case 5:
                $update['arrive_time'] = time();
                $update['arrive_img'] = $input['arrive_img'];
                $update['arr_lng']    = !empty($input['arr_lng'])?$input['arr_lng']:0;
                $update['arr_lat']    = !empty($input['arr_lat'])?$input['arr_lat']:0;
                $update['arr_address']= !empty($input['arr_address'])?$input['arr_address']:'';
                break;
            case 6:
                $update['start_service_time'] = time();
                break;
            case 7:
                $update['order_end_time'] = time();
                $update['end_lng']    = !empty($input['end_lng'])?$input['end_lng']:0;
                $update['end_lat']    = !empty($input['end_lat'])?$input['end_lat']:0;
                $update['end_address']= !empty($input['end_address'])?$input['end_address']:'';
                $update['end_img']    = !empty($input['end_img'])?$input['end_img']:'';
                break;
            case -1:
                $update['coach_refund_time'] = time();
                $update['coach_refund_text'] = !empty($input['coach_refund_text'])?$input['coach_refund_text']:'';
                break;
        }
        return $update;
    }
    /**
     * @author chenniang
     * @DataTime: 2021-07-11 23:18
     * @功能说明:技师佣金到账
     */
    public function coachBalanceArr($uniacid){
        $dis[] = ['uniacid','=',$uniacid];
        $dis[] = ['pay_type','=',7];
        $dis[] = ['have_tx','=',0];
//        $dis[] = ['can_tx_date','<',time()];
        $order = $this->where($dis)->field('admin_id,admin_cash,id,coach_id,service_price,car_price,true_service_price,true_car_price,admin_cash,coach_cash')->select()->toArray();
        if(!empty($order)){
            $refund_model= new RefundOrder();
            $coach_model = new Coach();
            $comm_model  = new Commission();
            $admin_model = new Admin();
            foreach ($order as $value){
                $refund_order = $refund_model->dataInfo(['order_id'=>$value['id'],'status'=>1]);
                if(empty($refund_order)){
                    Db::startTrans();
                    //分销佣金
                    $comm_model->successCash($value['id']);
                    //修改订单状态
                    $res = $this->where(['id'=>$value['id'],'have_tx'=>0])->update(['have_tx'=>1]);
                    //增加团长佣金
                    if($res!=0){
                        $cap_cash = $value['coach_cash'];
//                        $cap_cash = $value['true_service_price'];
//
                        $car_cash = $value['true_car_price'];
//                        $res = $coach_model->where(['id'=>$value['coach_id']])->update(['service_price'=>Db::raw("service_price+$cap_cash"),'car_price'=>Db::raw("car_price+$car_cash")]);
                        $res = $coach_model->where(['id'=>$value['coach_id']])->update(['service_price'=>Db::raw("service_price+$cap_cash"),'car_price'=>Db::raw("car_price+$car_cash")]);
                        if($res==0){
                            Db::rollback();
                        }
                        //给加盟商加佣金
                        if(!empty($value['admin_cash'])&&$value['admin_cash']>0&&!empty($value['admin_id'])){
                            $admin_cash = $value['admin_cash'];
                            $res = $admin_model->where(['id'=>$value['admin_id']])->update(['cash'=>Db::raw("cash+$admin_cash")]);
                            if($res==0){
                                Db::rollback();
                            }
                        }
                    }else{
                        Db::rollback();
                    }
                    Db::commit();
                }
            }
        }
        return true;
    }
    /**
     * @author chenniang
     * @DataTime: 2022-08-30 14:12
     * @功能说明:获取渠道商订单信息
     */
    public function channelData($channel_id,$input=[]){
        $dis[] = ['a.channel_id','=',$channel_id];
        $dis[] = ['a.pay_type','>',1];
        if(!empty($input['start_time'])&&!empty($input['end_time'])){
            $dis[] = ['a.create_time','between',"{$input['start_time']},{$input['end_time']}"];
        }
        $where = [];
        if(!empty($input['name'])){
            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];
            $where[] = ['a.order_code','like','%'.$input['name'].'%'];
        }
        $id = $this->alias('a')
            ->join('massage_service_order_goods_list b','a.id = b.order_id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->column('a.id');
        $service_price = $this->where('id','in',$id)->sum('true_service_price');
        $data['order_price'] = round($service_price,2);
        $data['order_count'] = $this->where('id','in',$id)->count();;
        return $data;
    }
}